const amapKey = "de8f014adc7c59857453b0bc8b7bc2a8";

Page({
    data: {
        orderId: '',
        orderDetail: {}
    },

    onLoad(options) {
        console.log(`🚀 [订单详情] 获取订单 ID: ${options.id}`);
        this.setData({ orderId: options.id });
        this.getOrderDetail();
    },

    getOrderDetail() {
        const that = this;
        wx.request({
            url: `http://localhost:8081/orders/${that.data.orderId}`,
            method: 'GET',
            success(res) {
                console.log("✅ [订单详情] 服务器返回数据: ", res);

                if (res.data.code === 0 || res.data.code === 200) {
                    let orderData = res.data.data;

                    let parsedOrder = {
                        orderId: orderData.bookingOrderId,
                        departureCoords: orderData.departureLongitudeLatitude || "",
                        arriveCoords: orderData.arriveLongitudeLatitude || "",
                        departure: "解析中...",
                        arrive: "解析中...",
                        pickUpTime: orderData.pickUpTime || "未知",
                        sendTime: orderData.sendTime || null,
                        totalPrice: orderData.totalPrice || 0,
                        remarks: orderData.remarks || "",
                        status: orderData.status || 0,
                        statusText: that.getOrderStatusText(orderData.status),
                        statusClass: that.getOrderStatusClass(orderData.status)
                    };

                    that.setData({ orderDetail: parsedOrder });

                    // 解析出发地
                    if (orderData.departureLongitudeLatitude) {
                        that.getAddressFromCoordinates(orderData.departureLongitudeLatitude, (address) => {
                            that.setData({ "orderDetail.departure": address });
                        });
                    }

                    // 解析目的地
                    if (orderData.arriveLongitudeLatitude) {
                        that.getAddressFromCoordinates(orderData.arriveLongitudeLatitude, (address) => {
                            that.setData({ "orderDetail.arrive": address });
                        });
                    }
                } else {
                    wx.showToast({
                        title: `获取订单失败: ${res.data.message || '未知错误'}`,
                        icon: 'none'
                    });
                }
            },
            fail(err) {
                console.error("❌ [订单详情] 网络请求失败: ", err);
                wx.showToast({
                    title: '网络错误，请检查后端',
                    icon: 'none'
                });
            }
        });
    },

    getAddressFromCoordinates(coordinate, callback) {
        if (!coordinate.includes(",")) {
            callback("未知地址");
            return;
        }
        const [lng, lat] = coordinate.split(",");
        console.log(`📍 [前端] 解析经纬度: ${lng}, ${lat}`);

        wx.request({
            url: `https://restapi.amap.com/v3/geocode/regeo`,
            method: "GET",
            data: { key: amapKey, location: `${lng},${lat}` },
            success: (res) => {
                console.log("✅ [前端] 逆地理编码成功: ", res);
                callback(res.data.status === "1" ? res.data.regeocode.formatted_address : "未知地址");
            },
            fail: () => {
                console.error("❌ [前端] 逆地理编码失败");
                callback("未知地址");
            }
        });
    },

    getOrderStatusText(status) {
        const statusMap = {
            0: "待支付",
            1: "已支付",
            2: "已取消"
        };
        return statusMap[status] || "未知";
    },

    getOrderStatusClass(status) {
        const statusClassMap = {
            0: "status-unpaid",
            1: "status-paid",
            2: "status-cancelled"
        };
        return statusClassMap[status] || "";
    }
});
